﻿' ******************************************************************************
' ** 
' **  Yahoo! Managed
' **  Written by Marius Häusler 2011
' **  It would be pleasant, if you contact me when you are using this code.
' **  Contact: YahooFinanceManaged@gmail.com
' **  Project Home: http://code.google.com/p/yahoo-finance-managed/
' **  
' ******************************************************************************
' **  
' **  Copyright 2011 Marius Häusler
' **  
' **  Licensed under the Apache License, Version 2.0 (the "License");
' **  you may not use this file except in compliance with the License.
' **  You may obtain a copy of the License at
' **  
' **    http://www.apache.org/licenses/LICENSE-2.0
' **  
' **  Unless required by applicable law or agreed to in writing, software
' **  distributed under the License is distributed on an "AS IS" BASIS,
' **  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' **  See the License for the specific language governing permissions and
' **  limitations under the License.
' ** 
' ******************************************************************************


Namespace YahooManaged.Search.Diverse.API



    Public Class RelatedSuggestionsDownload
        Inherits Base.Download
        Public Event AsyncDownloadCompleted(ByVal sender As Base.Download, ByVal e As SuggestionsDownloadCompletedEventArgs)

        Private mSearchHelper As New SearchHelper

        ''' <summary>
        ''' Default constructor
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub New()
        End Sub

        Public Function Download(ByVal query As String, ByVal server As Server) As SuggestionsResponse
            Return Me.ToResponse(MyBase.DownloadStream(Me.DownloadUrl(query, server)))
        End Function

        Public Overloads Sub DownloadAsync(ByVal query As String, ByVal searchSvr As Server, Optional ByVal userArgs As Object = Nothing)
            Dim args As New AsyncDownloadArgs(userArgs, query) With {.SearchServer = searchSvr}
            MyBase.DownloadStreamAsync(Me.DownloadUrl(args.Query, args.SearchServer), args)
        End Sub


        Private Sub DownloadAsync_Completed(ByVal sender As Base.Download, ByVal e As Base.StreamDownloadCompletedEventArgs) Handles MyBase.AsyncStreamDownloadCompleted
            Dim dlArgs As AsyncDownloadArgs = DirectCast(e.UserArgs, AsyncDownloadArgs)
            Dim args As New SuggestionsDownloadCompletedEventArgs(dlArgs.UserArgs, Me.ToResponse(e.Response), dlArgs.Query, dlArgs.SearchServer)
            RaiseEvent AsyncDownloadCompleted(Me, args)
        End Sub


        Private Function DownloadUrl(ByVal query As String, ByVal srv As Server) As String
            If srv = Server.YQL Then
                Return mHelper.YqlUrl("*"c, "yahoo.search.suggestions", "command=""" & query & """"c, Nothing, False)
            Else
                Dim url As New Text.StringBuilder()
                url.Append("http://sugg.")
                url.Append(mHelper.ServerString(srv))
                url.Append("search.yahoo.com/gossip-")
                If srv = Server.USA Then
                    url.Append("us")
                Else
                    url.Append(mHelper.ServerString(srv).Replace(".", ""))
                End If
                url.Append("-sayt/?output=xml&nresults=10")
                url.Append("&command=")
                url.Append(Uri.EscapeDataString(query))
                Return url.ToString
            End If
        End Function

        Private Function ToResponse(ByVal resp As Base.StreamResponse) As SuggestionsResponse
            Dim lst As New List(Of String)
            Dim results = mHelper.GetResultsFromXml(resp.Result, "s")
            For Each resultNode In results
                Dim att As String = mHelper.GetXmlAttributeValue(resultNode, "k")
                If att <> String.Empty Then lst.Add(att)
            Next
            Return New SuggestionsResponse(resp.Connection, lst.ToArray)
        End Function

        Private Class AsyncDownloadArgs
            Inherits Base.DownloadEventArgs
            Public Query As String
            Public SearchServer As Server = Server.YQL
            Public Sub New(ByVal userArgs As Object, ByVal text As String)
                MyBase.New(userArgs)
                Me.Query = text
            End Sub
        End Class

    End Class



    Public Class SuggestionsResponse
        Inherits Base.Response


        Public Overloads ReadOnly Property Result() As String()
            Get
                Return TryCast(MyBase.Result, String())
            End Get
        End Property
        Friend Sub New(ByVal info As Base.ConnectionInfo, ByVal result As String())
            MyBase.New(info, result)
        End Sub
    End Class



    Public Class SuggestionsDownloadCompletedEventArgs
        Inherits Base.DownloadCompletedEventArgs
        Private mQuery As String = String.Empty
        Private mServer As Server

        Public ReadOnly Property Query() As String
            Get
                Return mQuery
            End Get
        End Property
        Public ReadOnly Property Server() As Server
            Get
                Return mServer
            End Get
        End Property
        Public Overloads ReadOnly Property Response() As SuggestionsResponse
            Get
                Return DirectCast(MyBase.Response, SuggestionsResponse)
            End Get
        End Property

        Friend Sub New(ByVal userArgs As Object, ByVal resp As SuggestionsResponse, ByVal query As String, ByVal server As Server)
            MyBase.New(userArgs, resp)
            mQuery = query
            mServer = server
        End Sub
    End Class


End Namespace